package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {
    @Value("$(sms.url)")
    private String smsUrl;
    @Value("$(sms.appkey)")
    private String appkey;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private RegionRepository repository;

    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        Region region =repository.findById(id).orElse(null);
        return region;
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //分页查询
        //查询对象
        //1: 查询总数:total
        Query query = new Query();
        long total = template.count(query, Region.class);
        if(total == 0){
            return Page.empty();  //空的分页对象
        }
        //2: 每页显示条数集合: list
        //设置页面显示条数, 还有当前页
        //1 当前页 2 每页的条数 3 排序规则 4 排序字段
        //分页参数对象
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Region> list = template.find(query, Region.class);

        //3:封装page对象
        return new PageImpl<Region>(list,pageable,total);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (!(StringUtils.hasLength(region.getId()))){
            region.setId(null);
            this.save(region);
        }else {
            this.update(region);

        }
    }

    @Override
    public void changeHotValue(int hot, String id) {
        Region region = this.get(id);
        region.setIshot(hot);
       this.update(region);
    }

    @Override
    public List<Region> queryHotRegion() {
        //状态是热门 通过序号排序
        return repository.findByIshotOrderBySequence(Region.STATE_HOT);
    }






}
